﻿using Business;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace BVVD_Website.ql_ketqua_hoctap
{
    public partial class frmGiayNhanxet : System.Web.UI.Page
    {
        public static string mfrm = "MNU028";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grvGiayNhanxet.Culture = new CultureInfo("vi-VN");
                grvGiayNhanxet.Rebind();

                BVVDDataContext db = new BVVDDataContext();
                var listLOPHOC = (from lh in db.LST_LOPHOCs
                                  where lh.TRANGTHAI.Equals("1")
                                  select lh).ToList();

                ddlLOPHOC.DataSource = listLOPHOC;
                ddlLOPHOC.DataTextField = "TENLH";
                ddlLOPHOC.DataValueField = "MALH";
                ddlLOPHOC.DataBind();

                fillgrvGiayNhanxet();
                grvGiayNhanxet.DataBind();

            }
        }



        protected void ddlLOPHOC_SelectedIndexChanged(object sender, Telerik.Web.UI.DropDownListEventArgs e)
        {
            //grvGiayNhanxet.DataSource = getData();
            fillgrvGiayNhanxet();
            grvGiayNhanxet.DataBind();
        }





        protected void grvGiayNhanxet_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {

            fillgrvGiayNhanxet();
        }

        protected void grvGiayNhanxet_ItemDataBound(object sender, GridItemEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            if (Session["user"] != null)
            {
                LST_NSD user = Session["user"] as LST_NSD;

                V_PHANQUYEN pq = (from p in db.V_PHANQUYENs
                                  where p.MAMN.Equals(mfrm) && p.MANSD.Equals(user.MANSD)
                                  select p).SingleOrDefault();
                if (pq != null)
                {
                    grvGiayNhanxet.MasterTableView.Columns.FindByUniqueName("btnDelete").Display = pq.DELETE > 0 ? true : false;
                    grvGiayNhanxet.MasterTableView.GetItems(GridItemType.CommandItem)[0].FindControl("lbtnSave").Visible = pq.EDIT > 0 && pq.ADD > 0 && pq.DELETE > 0 ? true : false;
                }
            }




            if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
            {
                
                string selectedLH = ddlLOPHOC.SelectedValue;
                GridEditFormItem editFormItem = e.Item as GridEditFormItem;
                GridDataItem parentItem = editFormItem.ParentItem;

                RadioButtonList rblTRANGTHAI = editFormItem.FindControl("rblTRANGTHAI") as RadioButtonList;
                RadTextBox txtMALH = editFormItem.FindControl("txtMALH") as RadTextBox;
                Label lblTENLH = editFormItem.FindControl("lblTENLH") as Label;

                RadDropDownList ddlMAHV = editFormItem.FindControl("ddlMAHV") as RadDropDownList;

                var list = (from hv in db.LST_HOCVIENs
                            join lhv in db.F_LOP_HOCVIENs on hv.MAHV equals lhv.MAHV into temp1
                            from tmp1 in temp1

                            select new
                            {
                                MALH = tmp1.MALH,
                                TENLH = tmp1.LST_LOPHOC.TENLH,
                                MAHV = hv.MAHV,
                                TENHV = hv.HODEM + " " + hv.TENHV,
                                FULLINFO = hv.MAHV + " - " + hv.HODEM + " " + hv.TENHV

                            }).ToList().Where(a => a.MALH == selectedLH).Distinct();

                ddlMAHV.DataSource = list;
                ddlMAHV.DataTextField = "FULLINFO";
                ddlMAHV.DataValueField = "MAHV";
                ddlMAHV.DataBind();

                if (e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem)
                {
                    if (ddlLOPHOC.SelectedIndex >= 0)
                    {
                        txtMALH.Text = ddlLOPHOC.SelectedValue;
                        lblTENLH.Text = ddlLOPHOC.SelectedText;

                    }
                    else
                    {
                        lblTENLH.Text = "<a href='/ql-ketqua-hoctap/frmGiayNhanxet.aspx'> Quay lại chọn lớp học </a>";
                    }

                }
                else
                {
                    Label lblTRANGTHAI = editFormItem["TRANGTHAI"].FindControl("lblTRANGTHAI") as Label;
                    rblTRANGTHAI.SelectedValue = lblTRANGTHAI.Text.Equals("ACTIVE") ? "1" : "0";
                    ddlMAHV.SelectedValue = editFormItem["MAHV"].Text;
                    ddlMAHV.Enabled = false;

                }

            }
        }

        protected void grvGiayNhanxet_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;

            F_GIAYNX gnx = new F_GIAYNX
            {
                SOGNX = (insertedItem.FindControl("txtSOGNX") as RadTextBox).Text,
                MALH = (insertedItem.FindControl("txtMALH") as RadTextBox).Text,
                MAHV = (insertedItem.FindControl("ddlMAHV") as RadDropDownList).SelectedValue,
                GHICHU = (insertedItem.FindControl("txtGHICHU") as RadTextBox).Text,
                NGAYNHAN = (insertedItem.FindControl("rdpNGAYNHAN") as RadDatePicker).SelectedDate,
                TRANGTHAI = (insertedItem.FindControl("rblTRANGTHAI") as RadioButtonList).SelectedValue

            };
            BVVDDataContext db = new BVVDDataContext();
            db.F_GIAYNXes.InsertOnSubmit(gnx);
            try
            {
                db.SubmitChanges();
                rnAlert.Text = "Thêm mới giấy nhận xét cho <font color='red'> " + gnx.LST_HOCVIEN.HODEM + " " + gnx.LST_HOCVIEN.TENHV + "</font> ở lớp <font color='red'> " + gnx.LST_LOPHOC.TENLH + "</font> thành công ";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra \n <br /> Nguyên nhân : " + ex.Message;

            }


            rnAlert.Show();
            grvGiayNhanxet.Rebind();
        }

        protected void grvGiayNhanxet_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string recid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["RECID"].ToString();
            BVVDDataContext db = new BVVDDataContext();
            F_GIAYNX gnx = (from dm in db.F_GIAYNXes
                            where dm.RECID.ToString().Equals(recid)
                            select dm).SingleOrDefault();
            db.F_GIAYNXes.DeleteOnSubmit(gnx);
            try
            {
                db.SubmitChanges();
                rnAlert.Text = "Xóa thành công giấy nhận xét số  <font color='red'> " + gnx.SOGNX + "</font>";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra. \n <br /> Nguyên nhân : " + ex.Message;
            }

            rnAlert.Show();
        }

        private void fillgrvGiayNhanxet()
        {
            BVVDDataContext db = new BVVDDataContext();
            var list = (from hv in db.F_LOP_HOCVIENs
                        join gcn in db.F_GIAYNXes on new { hv.MALH, hv.MAHV } equals new { gcn.MALH, gcn.MAHV }
                        into temp1
                        from tmp1 in temp1.DefaultIfEmpty()
                        select new
                        {
                            MALH = hv.MALH,
                            TENLH = hv.LST_LOPHOC.TENLH,
                            MAHV = hv.MAHV,
                            TENHV = hv.LST_HOCVIEN.HODEM + " " + hv.LST_HOCVIEN.TENHV,
                            SOGNX = tmp1.SOGNX,
                            NGAYNHAN = tmp1.NGAYNHAN,
                            TRANGTHAI = tmp1.TRANGTHAI != null ? tmp1.TRANGTHAI : "0",
                            RECID = tmp1.RECID != null ? tmp1.RECID : 0,
                            GHICHU = tmp1.GHICHU

                        }).ToList();

            
                grvGiayNhanxet.DataSource = list.Where(a => a.MALH.Equals(ddlLOPHOC.SelectedValue));


        }

        protected void grvGiayNhanxet_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                //Add new" button clicked
                e.Canceled = true;
                //Prepare an IDictionary with the predefined values
                System.Collections.Specialized.ListDictionary newValues = new
                System.Collections.Specialized.ListDictionary();
                newValues["MALH"] = "";
                newValues["TENLH"] = "";
                newValues["MAHV"] = "";
                newValues["TENHV"] = "";
                newValues["SOGNX"] = "";
                newValues["NGAYNHAN"] = "";
                //newValues["TRANGTH"] = "";
                newValues["GHICHU"] = "";
                //Insert the item and rebind
                e.Item.OwnerTableView.InsertItem(newValues);
            }

            if (e.CommandName.Equals("GiayNX"))
            {
                BVVDDataContext db = new BVVDDataContext();
                foreach (GridDataItem dr in grvGiayNhanxet.Items)
                {
                    string mahv = dr["MAHV"].Text;
                    string malh = dr["MALH"].Text;
                    string trangthai = dr["TRANGTHAI"].Text;
                    string ghichu = dr["GHICHU"].Text;
                    //DateTime ngaythi = rdpNGAYTHI.SelectedDate.Value;
                    DateTime ngaynhan = Convert.ToDateTime((dr.FindControl("txtNGAYNHAN") as RadDatePicker).IsEmpty ? DateTime.Now : (dr.FindControl("txtNGAYNHAN") as RadDatePicker).DbSelectedDate);
                    string sognx = (dr.FindControl("txtGNX") as RadTextBox).Text;

                    //string lblTRANGTHAI = (dr.FindControl("txtGCN") as RadTextBox).Text
                    F_GIAYNX obj = new F_GIAYNX
                    {
                        MAHV = mahv,
                        MALH = malh,
                        NGAYNHAN = ngaynhan,
                        SOGNX = sognx,
                        TRANGTHAI = String.IsNullOrEmpty(trangthai) ? "1" : trangthai,
                        GHICHU = String.IsNullOrEmpty(ghichu) ? "" : ghichu
                    };
                    checkRowExist(obj);


                }
                grvGiayNhanxet.Rebind();
                rnAlert.Text = "Lưu trữ thông tin giấy nhận xét thành công ";
                rnAlert.Show();

            }
        }
        private string checkRowExist(F_GIAYNX fc)
        {
            BVVDDataContext db = new BVVDDataContext();
            F_GIAYNX value = (from ck in db.F_GIAYNXes
                              where ck.MALH.Equals(fc.MALH)
                                      && ck.MAHV.Equals(fc.MAHV)
                              select ck).SingleOrDefault();
            if (value == null)
            {
                if (!String.IsNullOrEmpty(fc.SOGNX))
                {
                    db.F_GIAYNXes.InsertOnSubmit(fc);
                    db.SubmitChanges();
                    return "Add";
                }
                else {
                    return "Dont Save";
                }
            }
            else if (!value.SOGNX.Equals(fc.SOGNX) || !value.NGAYNHAN.Equals(fc.NGAYNHAN))
            {
                value.SOGNX = fc.SOGNX;
                value.NGAYNHAN = fc.NGAYNHAN;
                db.SubmitChanges();
                return "Update";
            }
            else
            {

                return "Cancel";
            }

        }

        protected void grvGiayNhanxet_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            GridEditableItem editedItem = e.Item as GridEditableItem;
            string recid = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["RECID"].ToString();

            F_GIAYNX gnx = (from item in db.F_GIAYNXes
                            where item.RECID.ToString().Equals(recid)
                            select item).SingleOrDefault();


            try
            {

                gnx.SOGNX = (editedItem.FindControl("txtSOGNX") as RadTextBox).Text;
                gnx.NGAYNHAN = Convert.ToDateTime((editedItem.FindControl("rdpNGAYNHAN") as RadDatePicker).DbSelectedDate);
                gnx.GHICHU = (editedItem.FindControl("txtGHICHU") as RadTextBox).Text;
                gnx.TRANGTHAI = (editedItem.FindControl("rblTRANGTHAI") as RadioButtonList).SelectedValue;
                db.SubmitChanges();
                rnAlert.Text = "Cập nhật giấy nhận xét thành công học viên có mã  <font color='red'> " + gnx.MAHV + "</font>";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra. \n <br /> Nguyên nhân : " + ex.Message;
            }

            rnAlert.Show();
        }

        
    }
}